package dp.mobile.eden;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ListView;
import dp.mobile.comm.RestClient;
import dp.mobile.level.Level;
import dp.mobile.level.LevelArrayAdapter;
import dp.mobile.level.LevelListViewItem;
import dp.mobile.system.SoundManager;
import dp.mobile.system.Utilities;
import dp.mobile.system.XMLReader;

public class SkirmishLevelSelectAct extends Activity {
	private static final int MSG_WHAT_LEVEL_LIST_START = 0;
	private static final int MSG_WHAT_LEVEL_LIST_RECEIVED = 1;
	private static final int MSG_WHAT_LEVEL_LIST_FAILED = 2;
	private static final int MSG_WHAT_LEVEL_START = 3;
	private static final int MSG_WHAT_LEVEL_RECEIVED = 4;
	private static final int MSG_WHAT_LEVEL_FAILED = 5;
	
	private static final String TAG = "Skirimish Select Act";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.skirmish_level_select);
		
		//mLinear = (LinearLayout)findViewById(R.id.level_linear);
		mIntentExtra = this.getIntent().getExtras().getInt(MainMenuAct.SKIRMISH_EXTRA);
		mListLevelView = (ListView) findViewById(R.id.list_level);
		
		if (mIntentExtra == (MainMenuAct.DOWNLOAD_LEVEL_INTENT))
			fetchLevelList();
		else if (mIntentExtra == (MainMenuAct.SELECT_LEVEL_INTENT))
			populateLinearWithDummy();
	}
	
	private Handler mLevelDownloadHandler = new Handler() {
		private ProgressDialog mDialog;
		
		@Override
		public void handleMessage(android.os.Message msg) {
			if (msg.what == MSG_WHAT_LEVEL_LIST_START) {
				isDownloadCancelled = false;
				mDialog = ProgressDialog.show(SkirmishLevelSelectAct.this, "Please wait", "Fetching level list...", true, true , new OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						isDownloadCancelled = true;
					}
				});
			}
			else if (msg.what == MSG_WHAT_LEVEL_LIST_RECEIVED) {
				mDialog.dismiss();
				mListLevelAdapter = new LevelArrayAdapter(SkirmishLevelSelectAct.this, mOnlineLevels);
				mListLevelView.setAdapter(mListLevelAdapter);
			}
			else if (msg.what == MSG_WHAT_LEVEL_LIST_FAILED) {
				mDialog.dismiss();
				if (!isDownloadCancelled) {
	 				AlertDialog.Builder tBuilder = new AlertDialog.Builder(SkirmishLevelSelectAct.this);
					tBuilder.setCancelable(true);
					tBuilder.setTitle("Failed");
					tBuilder.setMessage("Unable to fetch list. Please check you internet connection");
					tBuilder.show();
				}
			}
			else if (msg.what == MSG_WHAT_LEVEL_START) {
				mDialog = ProgressDialog.show(SkirmishLevelSelectAct.this, "Please wait", "Downloading level " +mSelectedLevelTitle+ " ...", true, true , new OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						isDownloadCancelled = true;
						AlertDialog.Builder tBuilder = new AlertDialog.Builder(SkirmishLevelSelectAct.this);
						tBuilder.setCancelable(true);
						tBuilder.setTitle("Cancelled");
						tBuilder.setMessage("Level download cancelled");
						tBuilder.show();
					}
				});
				isDownloadCancelled = false;
			}
			else if (msg.what == MSG_WHAT_LEVEL_RECEIVED) {
				mDialog.dismiss();
				AlertDialog.Builder tBuilder = new AlertDialog.Builder(SkirmishLevelSelectAct.this);
				tBuilder.setCancelable(true);
				tBuilder.setTitle("Success");
				tBuilder.setMessage("Level downloaded");
				tBuilder.show();
			}
			else if (msg.what == MSG_WHAT_LEVEL_FAILED) {
				mDialog.dismiss();
				AlertDialog.Builder tBuilder = new AlertDialog.Builder(SkirmishLevelSelectAct.this);
				tBuilder.setCancelable(true);
				tBuilder.setTitle("Failed");
				tBuilder.setMessage("Unable to download level. Please check your internet connection");
				tBuilder.show();
			}
		};
	};
	
	private ArrayList<LevelListViewItem> mOnlineLevels;
	
	protected void fetchLevelList() {
		mOnlineLevels = new ArrayList<LevelListViewItem>();
		
		Thread tDownloaderThread = new Thread() {
			@Override
			public void run() {
				mLevelDownloadHandler.sendEmptyMessage(MSG_WHAT_LEVEL_LIST_START);
				
				JSONObject tLevelsObject = RestClient.get("http://demeister.com/defenders/public/scripts/get_levels.php");
				if (tLevelsObject != null) {
					JSONArray  tIDs = tLevelsObject.names();
					
					for (int i = 0 ; i < tIDs.length() ; i++) {
						try {
							String tID = tIDs.getString(i);
							String tLevelTitle = tLevelsObject.getString(tID);
							
							mOnlineLevels.add(new LevelListViewItem(Integer.valueOf(tID), tLevelTitle, ""));
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
					mLevelDownloadHandler.sendEmptyMessage(MSG_WHAT_LEVEL_LIST_RECEIVED);
				}
				else
					mLevelDownloadHandler.sendEmptyMessage(MSG_WHAT_LEVEL_LIST_FAILED);
			}
		};
		
		tDownloaderThread.start();
	}
	
	public void downloadLevel(final int pLevelID , final String pLevelTitle) {
		mSelectedLevelTitle = pLevelTitle;
		Thread tLevelDownloader = new Thread() {
			@Override
			public void run() {
				mLevelDownloadHandler.sendEmptyMessage(MSG_WHAT_LEVEL_START);
				//Log.i("this" , RestClient.getResponseInputStream("http://demeister.com/defenders/public/scripts/file_get_contents.php?id=1"));
				InputStream tResponseInputStream = RestClient.getResponseInputStream("http://demeister.com/defenders/public/scripts/file_get_contents.php?id=" + pLevelID);
				if (tResponseInputStream != null) {
					try {
						if (!isDownloadCancelled) Utilities.writeNewFile(tResponseInputStream, pLevelTitle + ".xml", Utilities.LEVEL_FOLDER);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (!isDownloadCancelled) mLevelDownloadHandler.sendEmptyMessage(MSG_WHAT_LEVEL_RECEIVED);
				}
				else
					mLevelDownloadHandler.sendEmptyMessage(MSG_WHAT_LEVEL_FAILED);
			}
		};
		
		tLevelDownloader.start();
	}
	
	private void populateLinearWithDummy() {
		mListLevelItem = new ArrayList<LevelListViewItem>();
		
		File levelFolder = new File(Utilities.LEVEL_FOLDER); 
		String[] levelFiles = levelFolder.list();
		
		for (int i = levelFiles.length - 1; i >= 0; --i){
			final String levelFile = levelFiles[i];
			Log.d(TAG, "levelFolder levelFile = " + levelFolder + "/" + levelFile);
			Level level = new Level(XMLReader.instance().parseXML(levelFolder + "/" + levelFile));
			mListLevelItem.add(new LevelListViewItem(level.getName(), levelFile));
		}
		
		mListLevelAdapter = new LevelArrayAdapter(this, mListLevelItem);
		Log.d("SKIRMISH SELECT", mListLevelView == null ? "NULL" : "TIDAK NULL");
		mListLevelView.setAdapter(mListLevelAdapter);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		SoundManager.instance(getBaseContext()).temporarySetMute(true);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		SoundManager.instance(getBaseContext()).temporarySetMute(false);
	}
	
	//PROPERTIES
	//private LinearLayout mLinear;
	public  boolean		   isDownloadCancelled = false;
	private String mSelectedLevelTitle;
	public int	mIntentExtra;
	private ListView	mListLevelView;
	private ArrayList<LevelListViewItem> mListLevelItem;
	private LevelArrayAdapter mListLevelAdapter;
}